/**
* @description: 签到
* @author: zhaohui
* @data:2023年6月10日
* @remark:
**/
<template>
	<view class="app-container">
		<nav-bar title="签到" @goBack="goBack"></nav-bar>
		<view class="content">
			<view class="sing-in-msg">
				<text class="sing-in-time">
					{{singInData.signTime}}
				</text>
				<text class="sing-in-time" v-if="!showSingIn">
					{{singInData.signUserName}}
				</text>
			</view>

			<text class="sing-in-address">
				{{singInData.signAdress}}
			</text>
			<view class="map-content">
				<view class="map-top">
					<text></text>
					<text v-if="showSingIn" class="orientation"
						@click="changePositioning()">{{singInData.signAdress ? "重新定位":"定位"}}</text>
				</view>
				<view id="map_holder"></view>
			</view>
			<view class="sing-in-img">
				<view class="sing-in-img-title">
					签到图片
				</view>
				<view class="image-wrap">
					<view class="image-list">
						<view class="upload-button" v-for="(imgItem, index) in fileList" :key="index"
							@click.stop="imageHandle(index,imgItem,'CHOOSE')">
							<view v-if="imgItem.img && showSingIn" class="delete-icon"
								@click.stop="imageHandle(index,imgItem, 'DELETE')">
								×</view>
							<img v-if="imgItem.img" :src="imgItem.img" alt=""
								@click.stop="imageHandle(index,imgItem, 'PREVIEW')">
						</view>
					</view>

				</view>
			</view>
			<!-- <view class="sing-in" v-if="showSingIn">
				<view class="sing-in-button">
					<text>签到</text>
					<text>{{nowTime}}</text>
				</view>
				<view class="sign-in-status">
					{{signInStatus}}
				</view>
			</view> -->
		</view>
		<van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
			<van-swipe>
				<div v-for="(image, index) in fileList" :key="index">
					<van-swipe-item v-if="image" style="text-align: center;">
						<img :src="image.img" />
					</van-swipe-item>
				</div>
			</van-swipe>
		</van-popup>
		<footer>
			<van-button v-if="showSingIn" block @click="submit">提交</van-button>
		</footer>
	</view>
</template>

<script>
	import navBar from '../../../components/common/nav-bar.vue'
	import baseConfig from '../../../common/config'
	import wx from '../../../static/common_js/jweixin_1.0.0'
	import axios from 'axios'
	let config = {}
	baseConfig.getOptions.then(res => {
		config = res
	})
	import {
		Toast,
		Dialog
	} from 'vant'
	import {
		mapGetters
	} from 'vuex'
	export default {
		name: 'singIn',
		components: {
			navBar
		},
		data() {
			return {
				baseUrl: "",
				fileList: [{
					raw: null,
					img: '',
					type: ''
				}, ],
				signInStatus: '今日你还未签到',
				delList: [],
				nowTime: '', //实时签到时间
				receiveParam: null,
				showSingIn: false, //是否可以签到
				singInData: {
					signTime: '',
					signUserName: '',
					signAdress: '',
					location: "",
				}, //查看数据
				showPreview: false, //图片预览
				psmpCoordinates: null
			}
		},
		mounted() {
			this.singInData.signTime = this.getDate()
			this.initData()
		},
		onLoad(option) {
			this.getOrientation().then((res) => {
				this.initChart()
			}).catch(error => {

			})
			// this.setMark()

			this.receiveParam = JSON.parse(option.list)
			this.baseUrl = config.firstUrl
			// this.baseUrl = `http://${this.$apiRequest.bzhzyApi.fileUrl}`
		},
		computed: {
			...mapGetters(['userData'])
		},
		methods: {
			initChart() {
				if (typeof epgis === 'undefined') {
					// eslint-disable-next-line no-undef
					var cssurl = this.$Config.gisUrl
					// eslint-disable-next-line no-undef
					var jsurl = this.$Config.gisUrljs
					this.loadCss(cssurl, () => {
						this.loadJS(jsurl, () => {
							this.initMap()
						})
					})
				} else {
					this.initMap()
				}
			},
			loadJS(url, callback) {
				// eslint-disable-next-line one-var
				var script = document.createElement('script'),
					fn = callback || function() {}
				script.type = 'text/javascript'
				// IE
				if (script.readyState) {
					script.onreadystatechange = function() {
						if (
							script.readyState === 'loaded' ||
							script.readyState === 'complete'
						) {
							script.onreadystatechange = null
							fn()
						}
					}
				} else {
					// 其他浏览器
					script.onload = function() {
						fn()
					}
				}
				script.src = url
				document.getElementsByTagName('head')[0].appendChild(script)
			},
			loadCss(url, fn) {
				// var head = document.getElementsByTagName('head')[0];
				var link = document.createElement('link')
				link.type = 'text/css'
				link.rel = 'stylesheet'
				if (link.readyState) {
					link.onreadystatechange = function() {
						if (link.readyState === 'loaded' || link.readyState === 'complete') {
							link.onreadystatechange = null

							fn()
						}
					}
				} else {
					// 其他浏览器

					link.onload = function() {
						fn()
					}
				}
				link.href = url
				document.getElementsByTagName('head')[0].appendChild(link)
			},
			initMap() {
				// eslint-disable-next-line no-undef
				let centerMsg = [this.jd, this.wd]
				let that_ = this
				epgis.tokenTask
					.login(
						'd90b195097243a32bdd90bfe87f608b9',
						'414deabb87fc3fb2af81874250eb0a1a'
					)
					.then(function() {
						// center: [112.27293603983162, 37.947509995760996], //山西经纬度
						// eslint-disable-next-line no-undef
						window.PSMAP = new epgis.Map({
							container: 'map_holder',
							// style: _this.theme === 'dark' ? 'aegis://styles/aegis/StreetsDark' : 'aegis://styles/aegis/Streets',
							style: 'aegis://styles/aegis/Streets',
							zoom: 5,
							// maxZoom: 7.9,
							dragPan: true, // 地图是否可通过鼠标拖拽平移，默认为true
							doubleClickZoom: true, // 是否支持双击放大地图
							scrollZoom: true, // 是是否缩放
							center: centerMsg, //山西经纬度
							// center: [116.76, 37.05],
							// center: [119.86868, 30.77642],
							localIdeographFontFamily: 'Microsoft YoHei'
						})
						PSMAP.on('load', function(e) {
							//var serviceTask = new epgis.ServiceTask();
							//
							//先建立好画选中点的图层，然后之后再设置位置和移除
							PSMAP.loadImage(
								'https://map.sgcc.com.cn/products/js-sdk/v3/assets/images/markers_new2_4ab0bc5_78.png',
								function(error, image) {
									if (error) throw error
									PSMAP.addImage('poi', image)
									PSMAP.addLayer({
										id: 'choicePoid',
										type: 'symbol',
										source: {
											type: 'geojson',
											data: {
												type: 'FeatureCollection',
												features: []
											}
										},
										layout: {
											'icon-image': 'poi',
											'icon-size': 0.5,
											'icon-anchor': 'bottom',
											//"icon-offset":[0,0],
											'icon-ignore-placement': true
										}
									})
								}
							)
							that_.setMark()
						})
						PSMAP.addControl(
							new epgis.ScaleControl({
								maxWidth: 80,
								unit: 'metric'
							}),
							'bottom-left'
						)

						PSMAP.on('click', function(e) {
							var features = PSMAP.queryRenderedFeatures(e.point)
							console.log(features)
							console.log(e)
						})


					})

					.catch(err => {
						console.log(err)
					})
			},
			getOrientation() {
				return new Promise((resolve, reject) => {
					const that_ = this
					that_.singInData.signAdress = ""
					wx.getLocation({
						type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
						success: function(res) {
							that_.wd = res.latitude
							that_.jd = res.longitude
							that_.singInData.location = `${that_.jd},${that_.wd}`
							uni.request({
								url: 'https://restapi.amap.com/v3/geocode/regeo',
								data: {
									// 申请web服务API类型KEY
									key: '0ae40dcfc5916391f7fdb17939737c81',
									location: `${that_.jd},${that_.wd}`
								},
								success: function(res) {
									console.log('得到的信息是', res)
									that_.singInData.signAdress = res.data.regeocode
										.formatted_address
									resolve(res)
								}
							})
						},
						fail: function(res) {
							reject(res)
							console.log('getLocation end', res)
						}
					})
				})

			},
			setMark() {
				const convertTask = new epgis.ConvertTask()
				let cords = [this.jd + ',' + this.wd]
				convertTask
					.convertCoord([cords], {
						from: 1
					})
					.then(function(result) {
						//画点,且控制面板出现与否
						PSMAP.getSource('choicePoid').setData({
							type: 'FeatureCollection',
							features: [{
								type: 'Feature',
								geometry: {
									type: 'Point',
									coordinates: result[0]
								}
							}]
						})
						PSMAP.easeTo({
							center: result[0],
							zoom: 18
						})

					})

			},
			/**
			 * 定位+mark
			 */
			changePositioning() {
				this.getOrientation().then(() => {
					this.setMark()
				}).catch(error => {

				})

			},
			goBack() {
				uni.navigateBack()
			},
			/**
			 * 通知上一个页面刷新数据
			 */
			back() {
				let pages = getCurrentPages()
				let prevPage = pages[pages.length - 2] //上一个页面
				prevPage.isRefresh = true
				uni.navigateBack()
			},
			/**
			 * flowState 0：未开始；1：执行中；2：已完成
			 */
			initData() {
				//查看
				if (this.receiveParam.flowState === '2') {
					this.showSingIn = false
					//签到id
					let param = {
						workPlanId: this.receiveParam.OBJID
					}
					this.$apiRequest.bzhzyApi
						.selectSignIn(param)
						.then(res => {
							this.singInData = res.data
							if (res.data.url.length > 0) {
								this.fileList[0]["img"] = this.baseUrl + res.data.url[0].filePath
								this.jd = res.data.signCoordinate.split(',')[0]
								this.wd = res.data.signCoordinate.split(',')[1]
								this.initChart()
							}
						})
						.catch(error => {})
				} else {
					//签到
					this.showSingIn = true
					// this.nowTimes()
				}
			},
			afterRead(file) {
				fileList.push(file)
			},
			/**
			 * 签到
			 */
			singIn() {
				Toast.loading({
					duration: 0,
					message: '加载中...',
					forbidClick: true
				})

				// let startTime = this.dateToTimestamp(this.receiveParam.PLANSTARTTIME)
				// let endTime = this.dateToTimestamp(this.receiveParam.PLANENDTIME)
				// let time = Date.parse(new Date()) / 1000
				// if (time >= startTime && time <= endTime) {

				// } else {
				// 	Dialog.confirm({
				// 			message: '签到失败',
				// 			confirmButtonColor: "#417adc"
				// 		})
				// 		.then(() => {})
				// 		.catch(() => {});
				// }
				// if (this.fileList[0].img === '') {
				// 	Toast.fail('请先上传图片')
				// 	return
				// }
				let formData = new FormData()
				formData.append('signType', '1')
				formData.append('signUserId', this.userData.userId)
				formData.append('signUserName', this.userData.userName)
				formData.append('signAdress', this.singInData.signAdress)
				formData.append('signCoordinate', this.singInData.location)
				formData.append('workPlanId', this.receiveParam.OBJID)
				formData.append('signTime', this.singInData.signTime)

				formData.append('files', this.fileList[0].raw)
				let config = {
					headers: {
						'Content-Type': 'multipart/form-data',
						Authorization: uni.getStorageSync('token') || ''
					}
				}
				let url = ''
				// #ifndef IGW
				url = '/ap//bzzy/web/wait/addSignIn'
				// #endif
				// #ifdef IGW
				url = `${this.baseUrl}/bzzy/web/wait/addSignIn`
				// #endif
				
				// url = `http://${this.$apiRequest.bzhzyApi.fileUrl}/bzzy/web/wait/addSignIn`
				

				axios.post(url, formData, config).then(res => {
					Toast.clear()
					Toast(res.data.msg)
					if (res.data.code == 0) {
						this.signInStatus = '已签到'
						// Toast.success(res.data.msg)
						this.back()
					} else if (res.data.code == 401) {
						Dialog.alert({
							message: "当前页面信息已失效",
							confirmButtonText: "重新加载",
							theme: "round-button",
						}).then(() => {
							uni.reLaunch({
								url: "/pages/SSOLogin"
							});
						})

					}
				}).catch(error => {
					Toast.clear()
					Toast("签到失败")
				})
			},
			/**
			 * 日期转时间戳
			 * @param {Object} datestr
			 */
			dateToTimestamp(datestr) {
				let date = new Date(datestr)
				let time = Date.parse(date)
				let timestamp = time / 1000
				return timestamp
			},
			submit() {
				// this.singInData.location="1"
				if (!this.singInData.location) {
					Toast.fail('请先进行定位')
					return
				}
				if (this.fileList[0].img === '') {
					Toast.fail('请先上传图片')
					return
				}
				Dialog.confirm({
						message: '提交后不可修改，是否确定提交？',
						confirmButtonColor: '#417adc'
					})
					.then(() => {
						// on confirm
						this.singIn()
					})
					.catch(() => {
						// on cancel
					})
			},
			/**
			 * @param {Object} imgIndex
			 * @param {Object} imgItem
			 * @param {Object} handleType
			 * showSingIn  是否可以签到
			 */
			imageHandle(imgIndex, imgItem, handleType) {
				if (handleType === 'CHOOSE' && this.showSingIn) {
					// let base64File =
					// 	''

					// let fileRaw = this.dataURLtoFile(base64File, `flash.jpeg`)
					// this.$set(this.fileList, imgIndex, {
					// 	raw: fileRaw,
					// 	img: base64File,
					// 	type: imgItem.type
					// })
					this.choosePhoto(imgIndex, imgItem)
				} else if (handleType === 'PREVIEW') {
					this.fileList = [imgItem]
					this.showPreview = true
				} else if (handleType === 'DELETE' && this.showSingIn) {
					this.$delete(this.fileList, imgIndex)
					this.fileList = [{
						img: '',
						raw: null,
						type: ''
					}]
				}
			},
			choosePhoto(imgIndex, imgItem) {
				let _this = this
				wx.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success: chooseImageRes => {
						wx.getLocalImgData({
							localId: chooseImageRes.localIds[0].toString(),
							success: function(res) {
								const localData = res.localData
								let imageBase64 = ''
								if (localData.indexOf('data:image') == 0) {
									//苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
									imageBase64 = localData
								} else {
									//此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
									//此时一个正常的base64图片路径就完美生成赋值到img的src中了
									imageBase64 =
										'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
								}
								let blob = _this.h5_url_to_blob(imageBase64)
								const photoName = `${new Date().getTime()}`
								_this.$set(_this.fileList, imgIndex, {
									raw: _this.dataURLtoFile(imageBase64,
										`${photoName}.jpeg`),
									img: URL.createObjectURL(blob),
									type: imgItem.type
								})
							}
						})
					},
					fail: error => {
						console.log(error)
					}
				})
			},
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], filename, {
					type: mime
				})
			},
			h5_url_to_blob(url) {
				let arr = url.split(',')
				let mime = arr[0].match(/:(.*?);/)[1]
				let bstr = atob(arr[1])
				let n = bstr.length
				let u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new Blob([u8arr], {
					type: mime
				})
			},
			/**
			 * 打卡默认时间显示
			 */
			getDate() {
				let time = new Date()
				let year = time.getFullYear()
				let month =
					time.getMonth() + 1 < 10 ?
					'0' + (time.getMonth() + 1) :
					time.getMonth() + 1
				let hh =
					time < 10 ?
					'0' + time.getHours() :
					time.getHours()
				let mm =
					time < 10 ?
					'0' + time.getMinutes() :
					time.getMinutes()
				let date = time.getDate() < 10 ? '0' + time.getDate() : time.getDate()
				return `${year}-${month}-${date}  ${hh}:${mm}`
			},
			/**
			 * @param {Object} timeStamp
			 * 签到时间
			 */
			timeFormate(timeStamp) {
				let hh =
					new Date(timeStamp).getHours() < 10 ?
					'0' + new Date(timeStamp).getHours() :
					new Date(timeStamp).getHours()
				let mm =
					new Date(timeStamp).getMinutes() < 10 ?
					'0' + new Date(timeStamp).getMinutes() :
					new Date(timeStamp).getMinutes()
				let ss =
					new Date(timeStamp).getSeconds() < 10 ?
					'0' + new Date(timeStamp).getSeconds() :
					new Date(timeStamp).getSeconds()
				this.nowTime = hh + ':' + mm
			},
			nowTimes() {
				this.timeFormate(new Date())
				setInterval(this.nowTimes, 1000)
				this.clear()
			},
			clear() {
				clearInterval(this.nowTimes)
				this.nowTimes = null
			}
		}
	}
</script>

<style lang="scss" scoped>
	.app-container {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		background: #ffffff;
		overflow: hidden;

		.content {
			display: flex;
			flex-direction: column;
			flex: 1;
			box-sizing: border-box;
			padding: px2vw(50);

			.sing-in-msg {
				display: flex;
				justify-content: space-between;
				width: 100%;
			}

			.sing-in-time,
			.sing-in-address {
				display: block;
				color: #666666;
				line-height: px2vw(62);
			}

			.sing-in-img-title::before {
				content: "*";
				color: #ff0000;

			}

			.sing-in-time {
				font-size: px2vw(40);
				opacity: 0.7;
				padding: 0 0 px2vw(10) 0;
			}

			.sing-in-address {
				font-size: px2vw(42);
			}

			.sing-in-map {
				width: 100%;
				height: px2vw(340);
				margin: px2vw(42) 0 0 0;
				border-radius: px2vw(20);
				background-color: #007aff;
			}

			.sing-in-img {
				margin-top: px2vw(100);
				width: 100%;

				.image-wrap {
					width: 100%;
					height: px2vw(215);
					display: flex;

					.image-list {
						width: 100%;
						display: flex;

						img {
							width: px2vw(215);
							height: px2vw(215);
							margin-right: px2vw(40);
							border-radius: px2vw(6);
						}

						.upload-button {
							width: px2vw(215);
							height: px2vw(215);
							background-size: cover;
							margin-right: px2vw(40);
							position: relative;
							background-image: url('../../../static/img/ywgj.png');
							margin-top: px2vw(49);

							.delete-icon {
								position: absolute;
								top: px2vw(-20);
								right: px2vw(-20);
								width: px2vw(40);
								height: px2vw(40);
								background-color: #ff4355;
								border-radius: 50%;
								color: #fff;
								display: flex;
								justify-content: center;
								align-items: center;
							}
						}
					}
				}
			}

			.van-uploader {
				margin-top: px2vw(55);
			}

			.sing-in {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin-top: px2vw(121);

				.sing-in-button {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					width: px2vw(320);
					height: px2vw(320);
					border-radius: 100%;
					background-image: linear-gradient(to top, #2edd91, #39d459);

					text:nth-child(1) {
						font-size: px2vw(54);
						line-height: px2vw(62);
						color: #ffffff;
					}

					text:nth-child(2) {
						font-size: px2vw(42);
						color: #ffffff;
						line-height: px2vw(62);
					}
				}

				.sign-in-status {
					font-size: px2vw(38);
					color: #666666;
					line-height: px2vw(62);
					opacity: 0.7;
					margin-top: px2vw(31);
				}
			}
		}

		.map-content {
			height: px2vh(340);
			background: #fff;
			margin-bottom: px2vh(30);
			border-radius: px2vh(20) px2vw(20);

			.map-top {
				display: flex;
				padding: px2vh(10) 0;

				text {
					flex: 1;
					color: #666;
					font-size: px2vh(42);
				}

				.orientation {
					color: #417adc;
					text-align: right;
				}
			}

			#map_holder {
				width: calc(100vw - #{px2vw(100)});
				width: 100%;
				// margin-left: px2vw(50);
				height: px2vh(340);
			}
		}

		footer {
			height: px2vw(155);
			padding-top: px2vw(45);

			/deep/ .van-button {
				position: fixed;
				bottom: px2vw(30);
				width: calc(100% - #{px2vw(60)});
				margin-left: px2vw(30);
				height: px2vw(120);
				color: #fff;
				background-color: #417adc;
				border: 1px solid #417adc;
				border-radius: px2vw(60);
			}
		}

		.van-preview-wrap {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;

			.van-swipe {
				width: 100%;
				height: 100%;

				.van-swipe-item {
					display: flex;
					// align-items: center;

					img {
						width: 100%;
						height: auto;
						max-width: 100%;
						min-height: 100%;
						object-fit: contain;
					}
				}
			}
		}

		.van-popup {
			background-color: rgba(0, 0, 0, 0.8);

			.van-cell {
				position: absolute;
				bottom: 0;
				border-top: 4px solid #eee;
				z-index: 3;
			}
		}
	}
</style>
